package com.imay.live.manager;

import android.support.v4.app.FragmentManager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.model.AdsModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ImayLogUtil;
import com.imay.live.utils.TimeUtil;
import com.imay.live.view.dialog.ShowAdsFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by nick on 2017/9/5.
 * 弹窗广告
 */

public class AdManager {

    //显示位置(1:动态页,2:发现页,3个人页,4:任意页面)
    public static final int TYPE_DYNAMICS = 1;
    public static final int TYPE_DISCOVERY = 2;
    public static final int TYPE_PROFILE = 3;
    public static final int TYPE_OTHER = 4;

    public List<AdsModel> adsModels;
    private UserInfoModel userInfo;
    private boolean hasShow;
    private OnShowAdListener onShowAdListener;


    private static class AdManagerHolder {
        private static final AdManager INSTANCE = new AdManager();
    }

    public static final AdManager getInstance() {
        return AdManagerHolder.INSTANCE;
    }

    private AdManager() {
        userInfo = UserInfoCache.getUserInfo();
        loadAds(null, -1);
    }

    private void loadAds(final FragmentManager manager, final int type) {
        ProtoRequestHelper.task(ProtoHttpFactory.getAds()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<List<AdsModel>> listResult = JSON.parseObject(data, new TypeReference<Result<List<AdsModel>>>() {
                }.getType());
                if (listResult.result == CodeSuccess) {
                    adsModels = new ArrayList<>(); //避免递归太多次
                    adsModels.addAll(listResult.data);
                    if (manager != null) {
                        showTabAd(manager, type);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                adsModels = new ArrayList<>();
            }
        });
    }

    public void showTabAd(FragmentManager manager, int type) {
        if (!AccountManager.getInstance().isLogined() || hasShow) {
            return;
        }
        if (adsModels == null) {
            loadAds(manager, type);
            return;
        }
        List<Integer> adIdList = initAdsList();
        Map<Integer, String> map = initAdsMap();
        AdsModel adsModel = getAdsModel(adIdList, map);
        if (adsModel != null && type == adsModel.getShowPage() && !hasShow) {
            ImayLogUtil.log("广告: " + adsModel.getId() + "");
            ShowAdsFragment fragment = ShowAdsFragment.newInstance(adsModel);
            DialogFragmentHelper.showDialogFragment(manager, fragment);
            hasShow = true;
            saveModel(adsModel, adIdList, map);
        } else {
            hasShowAdCallBack();
        }
    }

    private Map<Integer, String> initAdsMap() {
        Map<Integer, String> map;
        String jsonMap = PreferenceHelper.getInstance().getShowAdId();
        if (!TextUtils.isEmpty(jsonMap)) {
            map = JSON.parseObject(jsonMap, Map.class);
        } else {
            map = new HashMap<>();
        }
        return map;
    }

    private List<Integer> initAdsList() {
        List<Integer> adIdList;
        String json = PreferenceHelper.getInstance().getAdList();
        if (!TextUtils.isEmpty(json)) {
            adIdList = JSON.parseArray(json, Integer.class);
        } else {
            adIdList = new ArrayList<>();
        }
        return adIdList;
    }

    /**
     * 不管有没有显示广告, 都要回调, 用于显示建楼卡
     */
    private void hasShowAdCallBack() {
        if (onShowAdListener != null) {
            onShowAdListener.onShowAds();
        }
    }

    private AdsModel getAdsModel(List<Integer> adIdList, Map<Integer, String> map) {
        //       int showId = PreferenceHelper.getInstance().getShowAdId();
        AdsModel targetModel;
        targetModel = getModelFormList(adIdList, map);
//        if (showId !=0 && targetModel==null){ //如果第一次拿不到, 可能是显示了最后的, 把showId变为0 重新获取一次
//            targetModel = getModelFormList(0);
//        }
        return targetModel;
    }


    private AdsModel getModelFormList(List<Integer> adIdList, Map<Integer, String> map) {
        AdsModel targetModel = null;
//        boolean hasMate = false;//如果showId > 0 , 要检测是否已经匹配过, 拿匹配过的后面的值
        for (int i = 0; i < adsModels.size(); i++) {
            int adsModelid = adsModels.get(i).getId();
            AdsModel model = adsModels.get(i);

            if (userInfo != null) {//等级判断
                UserModel user = userInfo.getUser();
                if (model.getLiveLvMin() > userInfo.getUser().getLiveLevel() || model.getLiveLvMax() < user.getLiveLevel() || (model.getUserLvMin() > user.getUserLevel() || model.getUserLvMax() < user.getUserLevel())) {
                    continue;
                }
            }
            if (hasExist(adIdList, adsModelid)) {  //如果已经存在只显示一次的广告id. 则跳过
                continue;
            }
            if (hasExist(map, adsModelid)) {
                continue;
            }


            targetModel = model;
            break;
//            if (showId==0){
//                targetModel = model;
//                break;
//            }else if(adsModelid==showId ){
//                hasMate = true;
//                continue;
//            }else if(!hasMate){
//                continue;
//            }else{
//                targetModel = model;
//                break;
//            }
        }
        return targetModel;
    }

    private boolean hasExist(List<Integer> adIdList, int id) {
        if (adIdList != null) {
            for (Integer adId : adIdList) {
                if (id == adId) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean hasExist(Map<Integer, String> map, int id) {
        if (map != null) {
            if (map.containsKey(id)) {
                String timeStr = map.get(id);
                if (TimeUtil.getToday().equals(timeStr)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return false;
    }

    private void saveModel(AdsModel adsModel, List<Integer> adIdList, Map<Integer, String> map) {
        if (adsModel.getShowType() == 1) {
            adIdList.add(adsModel.getId());
            PreferenceHelper.getInstance().saveAdList(JSON.toJSONString(adIdList));
        } else {
            map.put(adsModel.getId(), TimeUtil.getToday());
            PreferenceHelper.getInstance().saveShowAdId(JSON.toJSONString(map));
        }
    }

    public interface OnShowAdListener {
        void onShowAds();
    }


    public void setOnShowAdListener(OnShowAdListener onShowAdListener) {
        this.onShowAdListener = onShowAdListener;
    }
}
